<template>
  <div class="scroll-view" ref="scrollRef">
    <div v-for="item of listData" :key="item.id" class="list-item">
      {{ item.text }}
    </div>
    <div class="bottom-box" v-if="!noData">Loading more...</div>
    <div class="bottom-box" v-if="noData">No more data...</div>
  </div>
</template>

<script>
export default {
  name: "MyList",
  props: ["data", "pageCount"],
  data() {
    return {
      startIndex: 0,
      listData: [],
      noData: false,
    };
  },
  methods: {
    //一次顯示5條數據的方法
    setListData() {
      // 最終的startIndex
      // 證明已經沒有數據
      if (this.startIndex > this.data.length - 1) {
        this.noData = true;
        return;
      }

      //[1,2,3,4,5,6,7,8,9,10]
      //第一次：索引0-5 取[1,2,3,4,5] -> push
      //第二次：索引6-10 取[6,7,8,9,10] -> push
      //...

      this.listData.push(
        ...this.data.slice(
          // 每次增加5條
          this.startIndex,
          (this.startIndex += this.pageCount)
        )
      );
    },

    loadMore() {
      // console.log(this.oScrollRef);
      //<div data-v-52de489d="" class="scroll-view"><div data-v-52de489d="" class="list-item">...</div>

      //計算
      const oScroll = this.oScrollRef;
      const listHeight = oScroll.clientHeight,
        scrollHeight = oScroll.scrollHeight,
        scrollTop = oScroll.scrollTop;

      //觸底時再次添加5條數據
      if (listHeight + scrollTop >= scrollHeight - 10) {
        this.setListData();
      }
    },
  },
  mounted() {
    this.oScrollRef = this.$refs.scrollRef;

    this.oScrollRef.addEventListener(
      "scroll",
      _.debounce(this.loadMore, 300),
      false
    );

    // 默認首次加載頁面顯示5條數據
    this.setListData();
  },
};
</script>

<style lang="scss" scoped>
body {
  margin: 0;
}

.scroll-view {
  height: 812px;
  overflow: auto;

  .list-item {
    height: 200px;
    border-bottom: 1px solid #ddd;
    text-align: center;
    line-height: 200px;
    font-size: 30px;
  }

  .bottom-box {
    height: 44px;
    border-bottom: 1px solid #ddd;
    text-align: center;
    line-height: 44px;
  }
}
</style>
